package cn.muqingfeng.bbs.fragment;

import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.ArticleListTO;
import cn.muqingfeng.api.to.ArticleTO;
import cn.muqingfeng.api.to.BaseArticleTO;
import cn.muqingfeng.api.to.Forum;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.adapter.ArticleAdapter;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.ArticleDetailActivity;
import cn.muqingfeng.bbs.ui.WebViewActivity;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView.IXListViewListener;
import cn.muqingfeng.util.ArticleCache;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

public class ArticleListFragment extends BaseFragment {
	private static final Object LOCK = new Object();
	private boolean isLoading = false;
	private View mContentView;
	private View mProgressLayout;
	private XListView mListLayout;
	private ArticleAdapter mAdapter;
	private String mUrl;
	private Bundle mParams = null;
	private int mCurrrentPage = 1;
	private String mFid;
	private boolean mToWebDetail = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (mContentView == null) {
			mContentView = View.inflate(inflater.getContext(), R.layout.article_list, null);
			mUrl = getArguments().getString(Constants.EXTRA_URL);
			mParams = getArguments().getBundle(Constants.EXTRA_BUNDLE);
			mToWebDetail = getArguments().getBoolean(Constants.EXTRA_TO_WEBDETAIL, false);
			setupViews();
		}
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		return mContentView;
	}

	private void setupViews() {
		mProgressLayout = mContentView.findViewById(R.id.progressLayout);
		mListLayout = (XListView) mContentView.findViewById(R.id.list_layout);
		mListLayout.setDivider(getResources().getDrawable(R.drawable.divider));
		mListLayout.setPullLoadEnable(true, mContext.getString(R.string.xlistview_footer_hint_normal));
		mListLayout.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Object obj = parent.getItemAtPosition(position);
				if (obj != null && obj instanceof ArticleTO) {
					ArticleTO articleTO = (ArticleTO) obj;
					if (mToWebDetail) {
						Intent intent = new Intent(getActivity(), WebViewActivity.class);
						String detailUrl = UriHelper.getWebDetailUrl(articleTO.getId());
						intent.putExtra(Constants.EXTRA_URL, detailUrl);
						startActivity(intent);

					} else {
						Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
						intent.putExtra(Constants.EXTRA_ARTICLE, articleTO);
						intent.putExtra(Constants.EXTRA_FID, mFid);
						startActivity(intent);
					}
				}
			}
		});
		mListLayout.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				long time = ArticleCache.getLastRefreshTime(mContext, mUrl);
				mListLayout.setRefreshTime(time);
				loadFromNetwork(1);
			}

			@Override
			public void onLoadMore() {
				loadFromNetwork(mCurrrentPage + 1);
			}
		});
		mAdapter = new ArticleAdapter(mContext);
		mListLayout.setAdapter(mAdapter);
		new LoadCacheNewsTask().execute();

	}

	class LoadCacheNewsTask extends AsyncTask<Void, Void, List<ArticleTO>> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected List<ArticleTO> doInBackground(Void... params) {
			List<ArticleTO> list = ArticleCache.getArticles(mContext, mUrl);
			return list;
		}

		@Override
		protected void onPostExecute(List<ArticleTO> result) {
			super.onPostExecute(result);
			if (result != null && !result.isEmpty()) {
				mAdapter.addNews(result);
				mAdapter.notifyDataSetChanged();
				mProgressLayout.setVisibility(View.GONE);
			}
			boolean noCache = result == null || result.isEmpty();
			long time = ArticleCache.getLastRefreshTime(mContext, mUrl);
			// 没有缓存或者过期
			if ((System.currentTimeMillis() - time > 5 * 60 * 1000) || noCache) {
				loadFromNetwork(1);
			}
		}

	}

	private void loadFromNetwork(final int page) {
		synchronized (LOCK) {
			if (isLoading)
				return;
			mCurrrentPage = page;
			isLoading = true;
			HashMap<String, String> params = new HashMap<String, String>();
			if (mParams != null) {
				for (String key : mParams.keySet()) {
					params.put(key, mParams.getString(key));
				}
			}
			params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
			params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(page));
			GsonRequest<BaseArticleTO> request = new GsonRequest<BaseArticleTO>(Method.POST, mUrl, new Listener<BaseArticleTO>() {

				@Override
				public void onResponse(BaseArticleTO response) {
					isLoading = false;
					if (getActivity() != null) {
						mProgressLayout.setVisibility(View.GONE);
						mListLayout.stopRefresh();
						mListLayout.stopLoadMore();
						ArticleListTO listTO = response.getArticleListTO();
						if (listTO != null) {
							List<ArticleTO> articles = listTO.getArticles();
							if (page == 1) {
								ArticleCache.saveArticle(mContext, mUrl, articles);
								mAdapter.clear();
							}
							Forum forum = listTO.getForum();
							if (forum != null) {
								mFid = forum.getFid();
							}
							mAdapter.addNews(articles);
							if (articles.size() <= 10) {
								mListLayout.setPullLoadEnable(false, null);
							} else {
								mListLayout.setPullLoadEnable(true, mContext.getString(R.string.xlistview_footer_hint_normal));
							}
						}
						mAdapter.notifyDataSetChanged();
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					isLoading = false;
					Toast.makeText(mContext, "请求失败，请重试!", Toast.LENGTH_SHORT).show();
					if (!isDetached()) {
						mListLayout.stopRefresh();
						mListLayout.stopLoadMore();
					}
				}
			}, params, BaseArticleTO.class);
			RequestHelper.startRequest(mContext, request);
		}
	}
}
